package gui;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;

import java.awt.Rectangle;
import javax.swing.JMenuItem;
import javax.swing.JList;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.JLabel;

import controle.ClienteProtocoloWorker;
import controle.Contato;
import controle.CriaConexaoListener;
import controle.CriaConexaoWorker;
import controle.IniciaConexaoChatListener;
import controle.IniciaConexaoChatWorker;
import controle.MensagemCliente;
import controle.MensagemServidor;
import controle.MensagemServidorBroadcast;

import javax.swing.JTable;
import javax.swing.DefaultListModel;

import usuario.Usuario;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.awt.Font;

public class ClientConnected extends JFrame {

	private static final long serialVersionUID = 1L;
	
	private ChatVoxGui chatVoxGui = null;

	private JPanel jContentPane = null;

	private Icon disconnectIcon = null;  //  @jve:decl-index=0:

	private JMenuBar jJMenuBar = null;

	private JMenu jMenu = null;
	
	private JMenu MenuChatVoip = null;

	private JMenuItem jMenuItem = null;

	private JList jList = null;

	private JLabel jLabel = null;
	
	private MensagemServidorBroadcast mensagemServidorBroadcast = null;  //  @jve:decl-index=0:
	
	private MensagemServidor mensagemServidor = null;

	private JScrollPane jScrollPane = null;
	
	private IniciaConexaoChatListener iniciaConexaoChatListener = null;
	
	private Usuario usuarioSessao = null;
	
	private JPopupMenu popupMenu = null;
	
	private JMenuItem voipItem = null;  //  @jve:decl-index=0:
	
	private JMenuItem chatItem = null;
	
	private JButton chatButton = null;
	
	private Icon userIcon = null;
	
	private List<Contato> contatos = null;

	/**
	 * This is the default constructor
	 */
	public ClientConnected(MensagemServidor mensagemServidor) {
		super();
		this.mensagemServidorBroadcast = new MensagemServidorBroadcast();
		this.mensagemServidor = mensagemServidor;
		this.usuarioSessao = mensagemServidor.getUsuario();
		
		this.contatos = this.mensagemServidor.getContatos();
		
		this.chatVoxGui = new ChatVoxGui(this.contatos, this.usuarioSessao);
		this.iniciaConexaoChatListener = new IniciaConexaoChatListener(this.chatVoxGui);
		this.iniciaConexaoChatListener.start();
		
		initialize();
		
		//adiciona um WindowListener no frame
		addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e)
		{
			String ConfirmaSaida = "Tem certeza que deseja sair do LiveVox? ";
	        String TituloPane = "Confirmação de saída";
	        int i=JOptionPane.showConfirmDialog(null,ConfirmaSaida,TituloPane,JOptionPane.CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);   
	         if(i==JOptionPane.OK_OPTION)
	         {
	        	MensagemCliente msgCliente = new MensagemCliente(usuarioSessao, 2);
	 			ClienteProtocoloWorker clienteProtocoloWorker = new ClienteProtocoloWorker(msgCliente);
	 			clienteProtocoloWorker.run();
	         }
	         System.exit(1);
			
		}
		});
	}
	
	
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(450, 700);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.disconnectIcon = new ImageIcon( getClass().getResource( "/live/Live/imagens/cadeado_aberto.jpg" ) );
		this.userIcon = new ImageIcon( getClass().getResource( "/live/Live/imagens/user.png" ) );
		
		this.setJMenuBar(getJJMenuBar());
		this.setResizable(false);
		this.setContentPane(getJContentPane());
		this.setTitle("LiveVox");
		
		this.setListaContatos();
	}

	private void setListaContatos() 
	{
		this.chatVoxGui.setContatos(this.mensagemServidor.getContatos());
		this.jLabel.setText(this.usuarioSessao.getEmail());
		this.jLabel.setIcon(this.userIcon);
		this.contatos = this.mensagemServidor.getContatos();
		for(int i = 0 ; i < contatos.size(); i++){
			if(contatos.get(i).getEmail().equals(this.usuarioSessao.getEmail())){
				contatos.remove(i);
			}
		}
		Iterator<Contato> iterator = contatos.iterator();
		Vector<String> vector = new Vector<String>(contatos.size());
		while(iterator.hasNext())
		{
			Contato contato = iterator.next();
			if(!contato.getEmail().equals(this.usuarioSessao.getEmail()))
			{
				vector.add(contato.getEmail() + " - " + contato.getNome());	
			}
		}
		this.jList.setListData(vector);
	}

	public void setListaContatos(MensagemServidorBroadcast mensagemBroadcast) 
	{
		this.chatVoxGui.setContatos(mensagemBroadcast.getContatos());
		this.mensagemServidorBroadcast = mensagemBroadcast;
		this.contatos = mensagemBroadcast.getContatos();
		for(int i = 0 ; i < contatos.size(); i++){
			if(contatos.get(i).getEmail().equals(this.usuarioSessao.getEmail())){
				contatos.remove(i);
			}
		}
		
		String salaVazia[]	=	new String[1];
		salaVazia[0]		= "Sala Vazia";
		
		if(contatos.size() > 0)
		{
			Iterator<Contato> iterator = contatos.iterator();
			Vector<String> vector = new Vector<String>(contatos.size());
					
			while(iterator.hasNext())
			{
				Contato contato = iterator.next();
				if(!contato.getEmail().equals(this.usuarioSessao.getEmail()))
				{
					vector.add(contato.getEmail() + " - " + contato.getNome());	
				}
				
			}
			
			this.jList.setListData(vector);
			
		}
		else
		{		
			jList.setListData(salaVazia);
		}
	}
	
	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jLabel = new JLabel();
			jLabel.setText("");
			jLabel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Usu�rio", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), new Color(51, 51, 51)));
			jLabel.setBounds(new Rectangle(16, 47, 407, 41));
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.setAutoscrolls(true);
			jContentPane.add(getJScrollPane(), null);
			jContentPane.add(getChatJButton(), null);
			jContentPane.add(jLabel, null);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jJMenuBar	
	 * 	
	 * @return javax.swing.JMenuBar	
	 */
	private JMenuBar getJJMenuBar() {
		if (jJMenuBar == null) {
			jJMenuBar = new JMenuBar();
			jJMenuBar.add(getJMenu());
		}
		return jJMenuBar;
	}

	/**
	 * This method initializes jMenu	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	private JMenu getJMenu() {
		if (jMenu == null) {
			jMenu = new JMenu("Arquivo");
			jMenu.setMnemonic('A');
			jMenu.setBounds(new Rectangle(0, 0, 73, 13));
			jMenu.add(getJMenuItem());
		}
		return jMenu;
	}

	/**
	 * This method initializes jMenuItem	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItem() {
		if (jMenuItem == null) {
			jMenuItem = new JMenuItem("Sair", this.disconnectIcon);
			jMenuItem.setMnemonic('S');
			jMenuItem.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					String ConfirmaSaida = " CONFIRMAR SAIDA ? ";
			        String TituloPane = "CONFIRMA��O DE SAIDA";
			        int i=JOptionPane.showConfirmDialog(null,ConfirmaSaida,TituloPane,JOptionPane.CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);   
			         if(i==JOptionPane.OK_OPTION)
			         {
			        	MensagemCliente msgCliente = new MensagemCliente(usuarioSessao, 2);
			 			ClienteProtocoloWorker clienteProtocoloWorker = new ClienteProtocoloWorker(msgCliente);
			 			clienteProtocoloWorker.run();
			         }
			         System.exit(0);
				}
			});
		}
		return jMenuItem;
	}

	protected void desconectar() {
		ClienteProtocoloWorker clienteProtocoloWorker = new ClienteProtocoloWorker( new MensagemCliente(this.usuarioSessao, 2) );
		System.exit(0);
	}


	/**
	 * This method initializes jList	
	 * 	
	 * @return javax.swing.JList	
	 */
	private JList getJList() {
		if (jList == null) {
			jList = new JList();
			jList.setBorder(BorderFactory.createLineBorder(Color.black, 2));
			jList.setModel(new DefaultListModel());
			jList.setDragEnabled(true);
			jList.add(new JScrollPane());
			
//			jList.addMouseListener(new java.awt.event.MouseAdapter() {
//				public void mouseClicked(java.awt.event.MouseEvent e) {
//					
//					int xPos = e.getX();
//					int yPos = e.getY();
//					System.out.println("x:" + xPos + " y: "+ yPos);
//					if(e.getButton() == e.BUTTON3)
//					{
//						jList.setSelectedIndex(yPos);
//						//mouseLeftClicked(e);
//					}
//				}
//			});
		}
		return jList;
	}

	protected void mouseLeftClicked(java.awt.event.MouseEvent e) 
	{
		initMenus();
		
		int xPos = e.getX();
		int yPos = e.getY();
		
		System.out.println(jList.getSelectedValue().toString());
		
		this.popupMenu.show(e.getComponent(), xPos, yPos);
	}

	private void initMenus() 
	{
		this.popupMenu = new JPopupMenu();
		this.voipItem = new JMenuItem("Voip");
		this.chatItem = new JMenuItem("Chat");
		this.popupMenu.add(this.chatItem);
		this.popupMenu.add(this.voipItem);	
		
	}


	private String getEmailContato() 
	{
		String substring = this.jList.getSelectedValue().toString();
		String cut[] = substring.split(" ");
		return cut[0];
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() 
	{
		if (jScrollPane == null) 
		{
			jScrollPane = new JScrollPane();
			jScrollPane.setBounds(new Rectangle(12, 105, 417, 473));
			jScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Contatos", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), new Color(51, 51, 51)));
			jScrollPane.setViewportView(getJList());
		}
		return jScrollPane;
	}

	protected void conversarVoip() {
		// TODO Auto-generated method stub
		
	}


	private JButton getChatJButton() {
		if (chatButton == null) {
			chatButton = new JButton("Conectar");
			chatButton.setBounds(new Rectangle(166, 604, 99, 30));
			chatButton.setBackground(Color.white);
			chatButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					conversarChat();
				}
			});
		}
		return chatButton;
	}

	protected void conversarChat() 
	{
		if(!this.jList.isSelectionEmpty())
		{
			int i = this.jList.getSelectedIndex();
			System.out.println("huaaaaaaaa " + this.contatos.get(i).getIp());
			IniciaConexaoChatWorker iniciaConexaoChatWorker = new IniciaConexaoChatWorker(this.contatos.get(i).getIp(), this.usuarioSessao);
			iniciaConexaoChatWorker.run();
			this.chatVoxGui.chatVoxGuiConecta(this.contatos.get(i), this.usuarioSessao); 
			this.chatVoxGui.setVisible(true);
			this.chatVoxGui.setEnabled(true);
			
		}
	}
	
}
